package com.example.lenovo.asia5b.ui.photoview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import fay.frame.ui.U;

/**
 * 图片查看器
 */
public class ImagePagerActivity extends FragmentActivity {
	private String bill_image;

	private static final String STATE_POSITION = "STATE_POSITION";
	public static final String EXTRA_IMAGE_INDEX = "image_index"; 
	public static final String EXTRA_IMAGE_URLS = "image_urls";

	private HackyViewPager mPager;
	private int pagerPosition;
	private TextView indicator;
	private Button button_dl_invocel;//下载图片

	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_detail_pager);

		bill_image = getIntent().getStringExtra("bill_image");

		pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
		final  ArrayList<String> urls = getIntent().getStringArrayListExtra(EXTRA_IMAGE_URLS);

		mPager = (HackyViewPager) findViewById(R.id.pager);
		ImagePagerAdapter mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), urls);
		mPager.setAdapter(mAdapter);
		indicator = (TextView) findViewById(R.id.indicator);
		button_dl_invocel = (Button) findViewById(R.id.button_dl_invocel);
		button_dl_invocel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				U.Toast(ImagePagerActivity.this, getResources().getString(R.string.ksxz) + "...");
				new Thread() {
					public void run() {
						try {
							String aa = indicator.getText().toString();
							if (!TextUtils.isEmpty(aa)) {
								String[] bb = aa.split("/");
								int cc = Integer.parseInt(bb[0]);
								if (cc == 0) {
									return;
								}
								Bitmap bitmap = loadImageFromUrl(urls.get(cc-1));
								String fileName = (new java.text.SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH)).format(new Date()) + Setting.imageFileNameFormatCode;
								saveFile(bitmap, fileName);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					};
				}.start();
			}
		});

		CharSequence text = getString(R.string.viewpager_indicator, 1, mPager.getAdapter().getCount());
		indicator.setText(text);
		// 更新下标
		mPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageSelected(int arg0) {
				CharSequence text = getString(R.string.viewpager_indicator, arg0 + 1, mPager.getAdapter().getCount());
				indicator.setText(text);
			}

		});
		if (savedInstanceState != null) {
			pagerPosition = savedInstanceState.getInt(STATE_POSITION);
		}

		mPager.setCurrentItem(pagerPosition);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_POSITION, mPager.getCurrentItem());
	}

	public Bitmap loadImageFromUrl(String url) throws Exception {
		final DefaultHttpClient client = new DefaultHttpClient();
		final HttpGet getRequest = new HttpGet(url);

		HttpResponse response = client.execute(getRequest);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != HttpStatus.SC_OK) {
			// System.out.println("Request URL failed, error code =" +
			// statusCode);
			Log.e("PicShow", "Request URL failed, error code =" + statusCode);
		}

		HttpEntity entity = response.getEntity();
		if (entity == null) {
			Log.e("PicShow", "HttpEntity is null");
		}
		InputStream is = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			is = entity.getContent();
			byte[] buf = new byte[1024];
			int readBytes = -1;
			while ((readBytes = is.read(buf)) != -1) {
				baos.write(buf, 0, readBytes);
			}
		} finally {
			if (baos != null) {
				baos.close();
			}
			if (is != null) {
				is.close();
			}
		}
		byte[] imageArray = baos.toByteArray();
		return BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length);
	}

	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==1){
//                U.Toast(context, "保存图片成功，路径："+ Setting.IMAGE_ROOTPATH);
				U.Toast(ImagePagerActivity.this, getResources().getString(R.string.xzcg)+Setting.IMAGE_ROOTPATH_2+getResources().getString(R.string.wjj));
			}else if(msg.what==0) {
				U.Toast(ImagePagerActivity.this, getResources().getString(R.string.xzsb));
			}
		};
	};

	/**
	 * 保存图片
	 * @param bm
	 * @param fileName
	 */
	public void saveFile(Bitmap bm, String fileName) {
		try {
			String path = Setting.IMAGE_ROOTPATH;
			File dirFile = new File(path);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			//6.0以上使用getExternalFilesDir()获得存储关联目录进行存储，可以省去获得运行时权限
			//现在暂时使用new File来保存图片
			File myCaptureFile = new File(path,fileName);
			//判断文件是否存在
			if(myCaptureFile.exists()){
				myCaptureFile.delete();
			}
			FileOutputStream bos = new FileOutputStream(myCaptureFile);
			bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
			bos.flush();
			bos.close();
			//把文件插入到系统图库
            MediaStore.Images.Media.insertImage(getContentResolver(), myCaptureFile.getAbsolutePath(), fileName, null);
			handler.sendEmptyMessage(1);
			//保存图片后发送广播通知更新数据库
			Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			Uri uri = Uri.fromFile(myCaptureFile);
			intent.setData(uri);
			ImagePagerActivity.this.sendBroadcast(intent);
//            Uri uri = Uri.fromFile(myCaptureFile);
//            AccountDetailsDetActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
		} catch (Exception e) {
			handler.sendEmptyMessage(0);
		}

	}

	private class ImagePagerAdapter extends FragmentStatePagerAdapter {

		public ArrayList<String> fileList;

		public ImagePagerAdapter(FragmentManager fm, ArrayList<String> fileList) {
			super(fm);
			this.fileList = fileList;
		}

		@Override
		public int getCount() {
			return fileList == null ? 0 : fileList.size();
		}

		@Override
		public Fragment getItem(int position) {
			String url = fileList.get(position);
			return ImageDetailFragment.newInstance(url);
		}

	}
}
